package server.model.connections;

import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;


public class ConnectionManager implements Runnable {

	private Socket sckClient;
	//private PrintWriter outStr;
	private Scanner inStr;
	private boolean finished;
	private RequestManager requestManager;
	private String ipHost;
	private Integer port;

	public ConnectionManager(Socket sck){
		this.sckClient=sck;
		this.ipHost=this.sckClient.getInetAddress().getHostAddress();
		this.port=this.sckClient.getLocalPort();
		this.requestManager=new RequestManager();
		try {
			//this.outStr=new PrintWriter(this.sckClient.getOutputStream());
			this.inStr=new Scanner(this.sckClient.getInputStream());
			System.out.println("[SERVER/INFO] Connected to: " + this.ipHost + ":" + this.port);
		} catch (IOException e) {
			e.printStackTrace(System.err);
		}
	}

	public void finish(){
		this.finished=true;
	}

	public boolean isFinished(){
		return this.finished;
	}

	@Override
	public void run() {
		//System.out.println("[SERVER/INFO] Thread " + Thread.currentThread() + " started.");
		try{
			while( (!this.finished) && (this.inStr.hasNextLine()) ){
				String request=this.inStr.nextLine();
				//System.out.println("[SERVER/INFO] Request received: \n" + request.replaceAll("_barraN_", "\n").replaceAll("_barraR_", "\r"));
				//System.out.println("[SERVER/INFO] Sending Response to: " + this.ipHost + ":" + this.port);
				this.requestManager.processRequest(request, this.sckClient.getOutputStream());
			}
		} catch (IOException e) {
			e.printStackTrace(System.err);
		}finally{
			try {
				this.sckClient.close();
				System.out.println("[SERVER/INFO] Disconnected from: " + this.ipHost + ":" + this.port);
				//System.out.println("[SERVER/INFO] Thread " + Thread.currentThread() + " ended.");
			} catch (IOException e) {
				e.printStackTrace(System.err);
			}
		}
	}
}
